<?php

namespace App\Store\Controllers\Order;

use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Order\OrderRecovery;
use App\Store\Models\Order\OrderRecoveryGoods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Order\OrderSales as ModelsOrderOrderSales;
use App\Store\Services\Order\OrderSales;

class OrderInfoController extends Controller
{

    /**
     * 回执单接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getinfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cp_id = $request->cp_id ?? 0;
        $type = $request->type ?? '';

        if ($order_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $list = [];
        if ($type == 'sales_order') {
            $withinfo = [
                'memberinfo',
                'storeinfo',
                'goodslist',
                'shoppingaccountinfo1',
                'recoverygoodslist',
                'sendgoodslist',
            ];
            $info = ModelsOrderOrderSales::query()
                ->with($withinfo)
                ->where(['id' => $order_id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->where('audit_status','<>',3)
                ->first()
                ->toArray();

            if (!empty($info['goodslist'])) {
                foreach ($info['goodslist'] as $v) {
                    $goodsinfo = !empty($v['goodsinfo'])?json_decode($v['goodsinfo'], true) : [];
                    $list[] = [
                        'type' => '新商品',
                        'goods_sn_code' => $v['goods_sn_code'] ?? '',
                        'goods_name' => $v['goods_name'] ?? '',
                        'weight' => $v['weight'] ?? '',
                        'cf_no' => $goodsinfo['cf_no'] ?? '',
                        // 销售单价
                        'price' => $v['price'] / 100 ?? '',
                        'count' => $v['count'] ?? '',
                        // 工费
                        'cost_price' => $v['is_gram'] == 1 ? ($v['cost_price'] / 100 ?? '') : $v['pieceprice_fee'] / 100,
                        //标签价
                        'label_price' => $v['label_price'] / 100 ?? '',
                        //销售金额
                        'total_money' => $v['total_money'] / 100 ?? '',
                        // 优惠金额
                        'discount_money' => $v['discount_money'] / 100 ?? '',
                        //实收金额
                        'real_total_money' => $v['real_total_money'] / 100 ?? '',
                    ];

                }

                // 旧料回收
                $recovery = [];
                if (!empty($info['recoverygoodslist'])) {
                    foreach ($info['recoverygoodslist'] as $re) {
                        $price = $type == 1 ? $re['price'] : $re['d_price'];
                        $recovery[] = [
                            'type' => '旧料',
                            'goods_sn_code' => empty($re['goods_sn_code'] ?? '') ? '旧料' : $re['goods_sn_code'],
                            'goods_name' => $re['goods_name'] ?? '',
                            'cf_no' => '',
                            // 销售单价
                            'price' => $price / 100 ?? '',
                            'count' => $re['count'] ?? '',
                            'weight' => $re['weight'] ?? 0,
                            // 工费
                            'cost_price' => '',
                            //标签价
                            'label_price' => '',
                            //销售金额
                            'total_money' => '',
                            // 优惠金额
                            'discount_money' => '',
                            //
                            'real_total_money' => -($re['money'] / 100),
                        ];
                    }
                }


                // 曾品的
                $sendArr = [];
                if (!empty($info['sendgoodslist'])) {
                    foreach ($info['sendgoodslist'] as $send) {
                        $goods = json_decode($send['send_goods_info'], true) ?? [];
                        $sendArr[] = [
                            'type' => '赠品',
                            'goods_sn_code' => '赠品',
                            'goods_name' => $goods['sendgoods_name'] ?? '',
                            // 销售单价
                            'price' => '',
                            'cf_no' => '',
                            'count' => $send['count'] ?? '',
                            'weight' => '',
                            // 工费
                            'cost_price' => '',
                            //标签价
                            'label_price' => '',
                            //销售金额
                            'total_money' => '',
                            // 优惠金额
                            'discount_money' => '',
                            //
                            'real_total_money' => 0
                        ];
                    }
                }

                $list = array_merge($list, $recovery, $sendArr);

            }
        } else {
            // 纯回收订单
            $info = OrderRecovery::query()
                ->with(['memberinfo', 'shoppingaccountinfo1', 'storeinfo', 'goodslist'])
                ->where(['id' => $order_id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->where('audit_status','<>',3)
                ->first()
                ->toArray();
            if (!empty($info['goodslist'])) {
                foreach ($info['goodslist'] as $v) {
                    $list[] = [
                        'type' => '纯回收',
                        'cf_no' => '',
                        'goods_sn_code' => $v['goods_sn_code'] ?? '',
                        'weight' => $v['weight'],
                        'price' => $v['price'] / 100,
                        'count' => $v['count'] ?? '',
                        'goods_name' => '',
                        'cost_price' => '',
                        'label_price' => '',
                        'total_money' => '',
                        'discount_money' => '',
                        'real_total_money' => -($v['money'] / 100),
                    ];


                }
            }
        }

        $detail['order_sn'] = $info['order_sn'];
        $detail['pay_type_name'] = $info['pay_type_name'];
        $detail['pay_type_id'] = $info['pay_type_id'];
        $payList = PaytypeList::query()
            ->where('cp_id', $cp_id)
            ->where('is_del', 1)
            ->pluck('paytype_name', 'id')
            ->toArray();

        $mixed_payment = !empty($info['mixed_payment'])? $info['mixed_payment']:[];

        $payment = [];
        if ($info['pay_type_id'] < 0 && !empty($mixed_payment)) {
            $payment = [];
            foreach ($mixed_payment as $pay => $val) {
                $payId = explode('_', $pay)[1] ?? 0;
                $paytype_name = $payList[$payId] ?? '';
                $payment[] = [
                    'pay_name' => $paytype_name,
                    'pay_money' => $val/100
                ];

            }
        }

        if($type == 'sales_order'){
            $detail['total_money'] = $info['pay_money']/100;
            $total_money =$detail['total_money'];
        }else{
            $total_money =$info['total_money']/100;
            $detail['total_money'] = -$total_money;

        }
        // 大写
        $detail['capital_money'] = $detail['total_money']>0?$this->num_to_rmb($total_money):'负'.$this->num_to_rmb(abs($total_money));
        $detail['mixed_payment'] = $payment;
        $detail['order_at'] = $info['order_at'];
        $detail['account_name'] = $info['shoppingaccountinfo1']['real_name'] ?? '';
        $detail['store_name'] = $info['storeinfo']['store_name'] ?? '';
        $detail['address_area'] = $info['storeinfo']['address_area'] ?? '';
        $detail['contact_phone'] = $info['storeinfo']['contact_phone'] ?? '';
        $detail['real_name'] = $info['memberinfo'] ? $info['memberinfo']['real_name'] : '';
        $detail['mobile'] = $info['memberinfo'] ? $info['memberinfo']['mobile'] : '';
        $detail['balance_money'] = $info['balance_money']??0;
        $detail['pointstobalance'] =$info['pointstobalance']??0;
        $detail['list'] = array_values($list);

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $detail]);
    }


    public function num_to_rmb($num)
    {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位

        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";

        }

        $i = 0;
        $c = "";
        while (1) {

            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }

            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);

            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }

            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }

        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }

        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }

        //将处理的汉字加上“整”

        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }

    }
}
